<template>
  <div class="app-container">
    <!-- 使用上传子组件 -->
    <!-- on-success：上传成功以后 -->
    <!-- before-upload：上传之前 -->
    <upload-excel-component :on-success="onSuccess" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
// 引入接口
import { importEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 处理excel表格数据,将中文键值转成英文
    transExcel(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      return results.map(item => {
        const obj = {}
        const contentKeys = Object.keys(item)// 每一项中文键值拿出来
        // 将时间转换成一个标准的时间戳
        contentKeys.forEach(key => {
          const transKey = userRelations[key]// 拿到对应英文名字
          if (transKey === 'timeOfEntry' || transKey === 'correctionTime') {
            obj[transKey] = new Date(formatExcelDate(item[key]))
          } else {
            // 转换好以后的key动态添加给obj
            obj[transKey] = item[key]
          }
        })
        return obj
      })
    },

    // 父级接收子组件传递的数据，进行逻辑的处理
    async onSuccess({ results, header }) {
      const arr = this.transExcel(results)
      console.log(arr)
      // console.log(results)
      // console.log(header)
      // 批量导入员工
      const res = await importEmployee(arr)
      console.log(res)
      this.$router.back()
      this.$message.success(res.message)
    }
  }
}
</script>

